package codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.example.imagine.step1.codec.ImageResponseDecoder;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * Created by ryan on 15-8-25.
 */
public class FileRespondDecoder extends CumulativeProtocolDecoder {

    private static final String DECODER_STATE_KEY = ImageResponseDecoder.class.getName() + ".STATE";

    private static class DecoderState {
        long offset = -1;
        long record;
    }

    @Override
    protected boolean doDecode(IoSession ioSession, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
        DecoderState decoderState = (DecoderState) ioSession.getAttribute(DECODER_STATE_KEY);
        if (decoderState == null) {
            decoderState = new DecoderState();
            ioSession.setAttribute(DECODER_STATE_KEY, decoderState);
        }
        if (decoderState.offset == -1) {
            if (in.remaining() >= 16) {
                decoderState.offset = in.getLong();
                decoderState.record = in.getLong();
            } else {
                return false;
            }
        }
        if (decoderState.offset != -1){
            if (in.prefixedDataAvailable(4)) {
                int length = in.getInt();
                byte[] bytes = new byte[length];
                in.get(bytes);
                FileRespond fr = new FileRespond(decoderState.offset, length, bytes, decoderState.record);
                out.write(fr);
                decoderState.offset = -1;
                return true;
            }
            return false;
        }
        return false;
    }
}
